<script setup>
import { ElMessage,ElMessageBox  } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue'
import { ref ,onBeforeMount, reactive, toRefs, computed} from 'vue';
import { da, vi } from 'element-plus/es/locales.mjs';
import { listHandler } from '../../api/generic.js';
import { deleteTableRow } from '../../utils/utils';
import Table from '../components/Table.vue';
import { object2List,list2Object } from '../../utils/utils';
import { getPVListHandler,getStorageClassListHandler } from '../../api/pv.js';
// import { listHandler } from '../../api/generic.js';
// import DialogYaml from '../components/DialogYaml.vue';
// import { obj2Yaml } from '../../utils/utils';
import { updatePVCHandler as updateHandler, createPVCHandler as createHandler } from '../../api/pvc';
import {useRouter} from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  item: {
    type: Object
  }
})

const data = reactive({
  clusterId: '',
  namespace: '',
  item: {
    apiVersion: 'v1',
    kind: 'PersistentVolumeClaim',
    metadata: {
      name: '',
      namespace:'',
      labels: {},
      annotations: {}
    },
    spec: {
      resources: {
        requests: {
          storage: '5Gi',
        },
        },
      },
      volumeMode: 'Filesystem',
      storageClassName: '',
      accessModes: ['ReadWriteMany'],
    },
  options: {
    labelList:[],
    volumeSourceSelected: {},
    annotationsList:[],
    rules: {
      name: [
            {required: true, message: '请输入PVC名称', trigger: 'blur'}
        ],
      capacity: [
          {required: true, message: '请输入PVC大小', trigger: 'blur'}
      ],
      storageclass: [
          {required: true, message: '请输入存储类', trigger: 'blur'}
      ],
    },
    accessModes: [
      {
        value: 'ReadWriteMany',
        label: '多节点读写',
      },
      {
        value: 'ReadWriteOnce',
        label: '单节点读写',
      },
      {
        value: 'ReadOnlyMany',
        label: '多节点只读',
      },
      {
        value: 'ReadWriteOncePod',
        label: '单Pod读写',
      },
    ],
    volumeType: [
      {
        value: 'Filesystem',
        label: '文件系统',
      },
      {
        value: 'Block',
        label: '块存储',
      },
    ],
    claimType: [
      {
        value: 'pv',
        label: '静态申请'
      },
      {
        value:'storageclass',
        label: '动态申请'
      }
    ],
    claimTypeSelected: 'storageclass',
    volumeSourceList: [],
  }
})
const itemRef = ref()
const activeName = ref('basic')
const labelConfig = ref('labels')
let yamlContent = ref('')
let showDetail = ref(false)

const submitRollback = (msg)=>{ 
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
    }
  )
    .then(() => {
      //跳转到对应的列表页
      router.replace({
        path: '/pvc/list',
        query: {
          clusterId: data.clusterId,
          namespace: data.namespace
        }
      })
    })
    .catch(() => {
      return
    })
}

const submitHandler = (tag) => {
  console.log('tag:', tag)
  console.log('item:', data.item)
  //把list转成object
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationsList)
  if (tag == 'yaml') {
    // 首先要把json转成yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      item: data.item,
    }
    if (props.method != "Update") {
        // 创建用户，异步的
        createHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
          // loading.value = false
          // emits('rollback')
        })
  } else {
      // 创建用户，异步的
      updateHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
      })
    }
  }

}

const submit = (tag)=> {
    itemRef.value.validate((valid)=>{
        // valid => true
        if(!valid){
        ElMessage({
                    message: "请完善表单内容",
                    type: 'warning',
                })
        }else {
          submitHandler(tag)
        }
    })
}
const rollback = (clusterId,namespace)=>{
  console.log('cluster id:', clusterId)
  data.clusterId = clusterId
  data.namespace = namespace
  data.item.metadata.namespace = namespace
}

const claimTypeChanged = ()=>{
  data.options.volumeSourceSelected = null
  data.item.spec.storageClassName = ''
}

const volumeSourceChanged = (val) =>{
  console.log(val)
  if (data.options.claimTypeSelected == 'pv'){
    data.item.spec.storageClassName = val.spec.storageClassName
  }else {
    data.item.spec.storageClassName = val.metadata.name
  }
}

const visibleChanged = (visible) => {
  if (visible){
    listHandler(data.clusterId,data.namespace,data.options.claimTypeSelected).then((res)=>{ 
    console.log("获取存储资源列表:",res.data.data.items)
    data.options.volumeSourceList = res.data.data.items
  })
  }
 
}

onBeforeMount(()=>{
  if (props.method != 'Create'){
    data.item = JSON.parse(JSON.stringify(props.item))
    data.options.labelList = object2List(data.item.metadata.labels)
    data.options.annotationsList = object2List(data.item.metadata.annotations)
  }
})  
const {options,item,clusterId,namespace} = toRefs(data)

</script>

<template>
  <CreateOrEditFrame
  :cluster-readonly="props.method == 'Update'"
  :namespace-readonly="props.method == 'Update'"
  @namespace-changed-rollback="rollback"
  >
  <!-- 头部插入内容 -->

   <template #main>
    <el-form :model="item"
    label-width="true"
    ref="itemRef">
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="基本配置" name="basic" style="height: 240px;">
        <el-row :gutter="5">
          <el-col :span="8">
              <el-form-item  :rules="options.rules.name" label="PVC名称" prop="metadata.name" required>
                  <el-input style="width: 280px;"  :disabled="props.method == 'Update'" v-model="item.metadata.name"></el-input>
              </el-form-item>
          </el-col>
          <!-- 选择申请类型 -->
          <el-col :span="8" v-if="props.method !='Update'">
              <el-form-item  label="申请类型" prop="">
                <el-select 
                  v-model="options.claimTypeSelected" 
                  @change="claimTypeChanged"
                  style="width: 280px;"
                  placeholder="选择申请类型">
                    <el-option 
                    v-for="item in options.claimType" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value">
                    </el-option>
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="8" v-if="props.method !='Update'">
              <el-form-item :rules="options.rules.storageclass"  label="选择资源" required prop="spec.storageClassName">
                <el-select 
                  v-model="options.volumeSourceSelected" 
                  style="width: 280px;"
                  @visible-change="visibleChanged"
                  @change="volumeSourceChanged"
                  value-key="metadata.name"
                  :placeholder="options.claimTypeSelected == 'pv' ? '请选择PV' : '请选择StorageClass'">
                    <el-option 
                    v-for="item in options.volumeSourceList" 
                    :key="item.metadata.name" 
                    :label="item.metadata.name" 
                    :value="item">
                    </el-option>
                </el-select>
                <!-- <el-select 
                  v-if="options.claimTypeSelected == 'pv'"
                  v-model="item.spec.storageClassName" 
                  style="width: 280px;"
                  placeholder="选择PV">
                    <el-option 
                    v-for="item in options.volumeSourceList" 
                    :key="item.spec.storageClassName" 
                    :label="item.metadata.name" 
                    :value="item.spec.storageClassName">
                    </el-option>
                </el-select> -->
              </el-form-item>
          </el-col>
          <el-col :span="8" v-if="props.method == 'Update'">
              <el-form-item label="大存储类小" prop="">
                  <el-input :disabled="true" style="width: 220px;" v-model="item.spec.storageClassName"></el-input>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="8">
              <el-form-item  :rules="options.rules.capacity" label="存储空间" prop="spec.resources.requests.storage" required>
                  <el-input style="width: 280px;"  v-model="item.spec.resources.requests.storage"></el-input>
              </el-form-item>
          </el-col>
          <!-- 选择申请类型 -->
          <el-col :span="8">
            <el-form-item  label="访问策略" prop="">
                <el-select 
                  v-model="item.spec.accessModes" 
                  multiple
                  collapse-tags
                  style="width: 280px;"
                  placeholder="选择访问策略">
                    <el-option 
                    v-for="item in options.accessModes" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value">
                    </el-option>
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item  label="存储类型"  prop=""> 
                <el-select 
                  v-model="item.spec.volumeMode" 
                  style="width: 280px;"
                  placeholder="选择存储类型">
                    <el-option 
                    v-for="item in options.volumeType" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value">
                    </el-option>
                </el-select>
              </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
              <el-form-item  :rules="options.rules.capacity" label="大小" prop="spec.capacity.storage" required>
                  <el-input style="width: 220px;" v-model="item.spec.capacity.storage"></el-input>
              </el-form-item>
          </el-col> -->
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="注释及标签" name="labels">
        <el-tabs v-model="labelConfig" tabPosition="left">
            <el-tab-pane label="标签配置" name="labels">
              <Table :list="options.labelList"></Table>
            </el-tab-pane>
            <el-tab-pane label="注释配置" name="annos">
              <Table :list="options.annotationsList"></Table>
            </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>

    <!-- yaml,创建 -->
    <el-form-item class="button-container" style="margin-top: 10px;">
      <el-button @click="submit('yaml')">Yaml</el-button>
      <el-button type="primary" @click="submit()">
        {{ props.method=="Update" ? "更新" : "创建" }}
      </el-button>

     </el-form-item>
    </el-form>
   </template>

  </CreateOrEditFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  :method="props.method"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
</template>

<style scoped>
.button-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中（如果需要） */
  gap: 10px;               /* 按钮之间的间距 */
}
</style>
